function addOrEdit(id) {
    if (id) {
        window.location.href = `./addOrEdit.html?${id}`
    } else {
        window.location.href = './addOrEdit.html?'
    }
}


function cancer() {
    window.location.href = './index.html'
}
$(() => {
    fn_list()
})

function fn_list(newdata) {
    $.get('http://localhost:8000/product', data => {
        if (newdata) {
            data = newdata
        }
        console.log(data);
        $(".d").remove()
        data.forEach(item => {
            let html =
                `
        <tr class="d">
        <td>${item.id}</td>
        <td>${item.title}</td>
        <td>${item.abstract}</td>
        <td>${item.details}</td>
        <td>${item.classify}</td>
        <td>${item.author}</td>
        <td>${item.createdAt}</td>
        <td>
            <input type="button" value="修改" onclick="addOrEdit(${item.id})">
            <input type="button" value="删除" onclick="del(${item.id})">
        </td>
    </tr>
        `
            $('#tb').append(html)
        });

    })
}
function find() {
    let keyword = $('#keyword').val()
    // console.log(keyword);
    $.get(`http://localhost:8000/product?keyword=${keyword}`, data => {
        fn_list(data)
    })
}

function del(id) {
    $.ajax({
        url: `http://localhost:8000/del`,
        type: 'delete',
        data: { id },
        success: data => {
            window.location.href = './index.html'
        }

    })
}

function save() {
    
    let obj = {
        title:$('#title').val(),
        abstract:$('#abstract').val(),
        details:$('#details').val(),
        classify:$('#classify').val(),
        author:$('#author').val()
    }
    let id=window.location.href.split('?')[1]
    if (id) {
        obj.id=id
    }
    $.ajax({
        url:`http://localhost:8000/save`,
        type:'put',
        data:obj,
        success:()=>{
            window.location.href='./index.html'
        }

    })

}